import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { fakeAccountLogin, getFakeCaptcha } from '@/services/api';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';

export default {
  namespace: 'login',

  state: {
    status: undefined,
    message: undefined,
    // loading: false,
  },

  effects: {
    *login({ payload }, { call, put }) {
      // console.log("登录请求返回值:", payload);
      const response = yield call(fakeAccountLogin, payload); //{code: 1118, message: "用户不存在"}{code: 1119, message: "密码不正确"}
      console.log('请求登录 ===>', response);
      if (response) {
        yield put({
          type: 'changeLoginStatus',
          payload: { ...response, type: payload.type },
        });
        // Login 登录成功
        if (response.message === '请求响应成功') {
          // sessionStorage.setItem('TOKENER',response.data.token);
          sessionStorage.setItem('LOGIN_INFO', JSON.stringify(response.data));
          // }
          // console.log("登录后取到token：",JSON.parse(sessionStorage.getItem("LOGIN_INFO")).token)

          reloadAuthorized();
          yield put(routerRedux.replace('/home'));
          // const urlParams = new URL(window.location.href);
          // const params = getPageQuery();
          // let { redirect } = params;
          // if (redirect) {
          //   const redirectUrlParams = new URL(redirect);
          //   if (redirectUrlParams.origin === urlParams.origin) {
          //     redirect = redirect.substr(urlParams.origin.length);
          //     if (redirect.match(/^\/.*#/)) {
          //       redirect = redirect.substr(redirect.indexOf('#') + 1);
          //     }
          //   } else {
          //     window.location.href = redirect;
          //     return;
          //   }
          // }
          // yield put(routerRedux.replace(redirect || '/home'));
        }
      } else {
        return false;
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },

    *logout(_, { put }) {
      // yield put({
      //   type: 'changeLoginStatus',
      //   payload: {
      //     status: false,
      //     currentAuthority: 'guest',
      //   },
      // });
      // reloadAuthorized();
      sessionStorage.clear(),
        yield put(
          routerRedux.push({
            pathname: '/user/login',
            search: stringify({
              redirect: window.location.hash,
              // redirect: window.location.href,
            }),
          })
        );
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      console.log('changeLoginStatus:', state, payload);
      // setAuthority(payload.currentAuthority);
      return {
        ...state,
        message: payload.message,
        type: payload.type,
        // status: payload.status,
      };
    },
  },
};
